//
//  ViewController.m
//  WKWebViewShowImageDemo
//
//  Created by Sven on 2021/7/21.
//

#import "ViewController.h"
#import <WebKit/WebKit.h>
@interface ViewController ()<WKUIDelegate,WKNavigationDelegate>

@property (nonatomic, strong) WKWebView     *webView;

@property (nonatomic, strong) WKUserScript  *userScript;

@property (nonatomic, strong) NSArray       *imageArray;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    
    NSString *htmlsTr = @"<p>但是对方是个仅当用户拥有了企业账号并登录成功，才能在我们的平台上办理业务，听起来似乎非常简单，毕竟用户体系是非常基础的模块了，那么我们遇到了哪些问题？</p>\n<p><img src=\"https://iwork-img-test.oss-cn-beijing.aliyuncs.com/caifu/crm/voucher/durian/durian2021071915370444.jpg?Expires=1942040537&amp;OSSAccessKeyId=LTAIezDDhCzqtdOq&amp;Signature=Y9fL9I8ssYiInHQGidVZbeTxCh4%3D\" alt=\"\" width=\"1000\" height=\"362\" /><p>但是对方是个仅当用户拥有了企业账号并登录成功，才能在我们的平台上办理业务，听起来似乎非常简单，毕竟用户体系是非常基础的模块了，那么我们遇到了哪些问题？</p><img src=\"https://iwork-img-test.oss-cn-beijing.aliyuncs.com/caifu/crm/voucher/durian/durian2021071915344819.jpg?Expires=1942040518&amp;OSSAccessKeyId=LTAIezDDhCzqtdOq&amp;Signature=4pyI9WorPh4OBcS2A%2BSosh4bU5c%3D\" alt=\"\" width=\"662\" height=\"445\" /><img src=\"https://iwork-img-test.oss-cn-beijing.aliyuncs.com/caifu/crm/voucher/durian/durian2021071915944013.jpg?Expires=1942040570&amp;OSSAccessKeyId=LTAIezDDhCzqtdOq&amp;Signature=sC5Yn19J4g16gsMJGGPnZ%2FCcw0k%3D\" alt=\"\" width=\"1149\" height=\"893\" /></p>\n<p><img src=\"https://iwork-img-test.oss-cn-beijing.aliyuncs.com/caifu/crm/voucher/durian/durian2021071915813951.jpg?Expires=1942040555&amp;OSSAccessKeyId=LTAIezDDhCzqtdOq&amp;Signature=HJAYMkWw4KRl%2BiaqTOWnYl7grP0%3D\" alt=\"\" width=\"917\" height=\"234\" /></p>";
    
    NSString *headerStr = @" <head><meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0,user-scalable=no'> <style>img{max-width: 100%; width:auto; height:auto;}</style></head>";
    NSString *htmlStr = [NSString stringWithFormat:@"%@%@",headerStr,htmlsTr];
    
    [self.view addSubview:self.webView];
    self.webView.frame = self.view.bounds;
    [self.webView loadHTMLString:htmlStr baseURL:nil];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureAction:)];
    tapGesture.numberOfTapsRequired = 1;
    tapGesture.delegate = (id)self;
    [self.webView addGestureRecognizer:tapGesture];
    
    
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    return YES;
}
- (void)tapGestureAction:(UITapGestureRecognizer *)recognizer{
    
    CGPoint touchPoint = [recognizer locationInView:self.view];
    NSString *imgURLJS = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", touchPoint.x, touchPoint.y];
    //跟着注入JS 获取 异步获取结果
    [self.webView evaluateJavaScript:imgURLJS completionHandler:^(id result, NSError * _Nullable error) {
        if (error == nil){
            NSString *url = result;
            if (url.length == 0){
                return ;
            }
            else{
                if (self.imageArray.count>0) {
                    NSInteger index = [self.imageArray indexOfObject:url];
                    NSLog(@"url____%@__index____%ld",url,(long)index);
                }
            }
        }
    }];
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    
    //修改字体颜色  #9098b8
    [ webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextFillColor= '#525255'"completionHandler:nil];
    //修改字体大小
//    [ webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '200%'"completionHandler:nil];
   

    [webView evaluateJavaScript:@"getImages()" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        NSMutableArray *mu_image = [NSMutableArray array];
        NSArray *imgSrcArray = [NSMutableArray arrayWithArray:[result componentsSeparatedByString:@"+"]];
        for (NSString *str in imgSrcArray) {
            if ([str containsString:@"http"]) {
                [mu_image addObject:str];
            }
        }
        self.imageArray = [NSArray arrayWithArray:mu_image];
        NSLog(@"imageArray____%@",self.imageArray);

    }];
}
- (WKWebView *)webView{
    if (_webView == nil) {
        WKWebViewConfiguration *configer = [[WKWebViewConfiguration alloc] init];
        configer.userContentController = [[WKUserContentController alloc] init];
        configer.preferences = [[WKPreferences alloc] init];
//        configer.preferences.javaScriptEnabled = YES;
        configer.preferences.javaScriptCanOpenWindowsAutomatically = NO;
        configer.allowsInlineMediaPlayback = YES;
        [configer.userContentController addUserScript:self.userScript];
        _webView = [[WKWebView alloc]initWithFrame:CGRectZero configuration:configer];
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
//        _webView.scrollView.scrollEnabled = NO;
    }
    return _webView;
}
- (WKUserScript *)userScript {
    if (!_userScript) {
        static  NSString * const jsGetImages =
        @"function getImages(){\
        var objs = document.getElementsByTagName(\"img\");\
        var imgScr = '';\
        for(var i=0;i<objs.length;i++){\
        imgScr = imgScr + objs[i].src + '+';\
        };\
        return imgScr;\
        };function registerImageClickAction(){\
        var imgs=document.getElementsByTagName('img');\
        var length=imgs.length;\
        for(var i=0;i<length;i++){\
        img=imgs[i];\
        img.onclick=function(){\
        window.location.href='image-preview:'+this.src}\
        }\
        }";
        _userScript = [[WKUserScript alloc] initWithSource:jsGetImages injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    }
    return _userScript;
}


@end
